﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace demo.EventTest
{
    public class Log
    {
        // 日志文件
        private string logFile = AppDomain.CurrentDomain.BaseDirectory + "log.txt";

        public Log(ConsoleManager cm)
        {
            cm.ConsoleEvent += WriteLog;
        }

        /// <summary>
        /// 事件处理方法，注意参数固定模式
        /// </summary>
        /// <param name="sender">事件的发送者</param>
        /// <param name="args">事件的参数</param>
        private void WriteLog(object sender, EventArgs args)
        {
            // 文件不存在的话则创建新文件
            if (!File.Exists(logFile))
            {
                using (FileStream fs = File.Create(logFile))
                {

                }
            }

            FileInfo fi = new FileInfo(logFile);

            using (StreamWriter sw = fi.AppendText())
            {
                ConsoleEventArgs cea = args as ConsoleEventArgs;
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "|" + sender.ToString() + "|" + cea.Message);
            }
        }
    }
}
